#!/usr/bin/python
#coding=utf-8
import os;
from video_lib.video_db import db_init
from video_lib.video_db.ray_video_table import Ray_Video_File
from video_lib.video_db.ray_video_table import Ray_Video_Album
from video_lib.video_db.ray_video_table import Ray_Video_In_Album
from video_lib.video_db.ray_video_table import Ray_Video_Category


from video_lib.video_db.movie_queue import movie_queue
from sqlalchemy import or_, and_, desc
from sqlalchemy.orm import sessionmaker
import shutil
import types
from shitao_add_video_to_group import add_video_to_group

import time
"""
	相册:album
		类型+用品牌+产品名称作为相册名称
	
"""
class video_publish(object):
	Publist_Session			= sessionmaker(bind= db_init.engine_publish)
	publish_session			= Publist_Session()
        Video_Session                  	= sessionmaker(bind= db_init.engine)
	video_session			= Video_Session()
	Publish_Video_Path		= "/srv/www/shitao.com/public_html/flash/modules/video/files/"

	def __init__(self,video):
		self.download_video		= video;
		self.ray_video			= Ray_Video_File(); #代表发布后的视频对象
		video_publish.publish_session.add(self.ray_video);
		self.download_video_name	= self.download_video.video_convertname
		self.download_video_jpg		= self.download_video.video_convertname.replace(".m4v",".jpg")
		self.download_video_jpg_small	= self.download_video.video_convertname.replace(".m4v","_small.jpg")
		self.publish_video_name		= "";
		self.publish_video_jpg		= "";
		self.publish_video_jpg_small	= "";
		self.publish_video_status	= False
		video_publish.video_session.add(self.download_video)
		return;
	def get_owner(self):
		return 1;
	def get_album_name(self):
		return self.download_video.video_product;
	def get_album(self):
		album_name	= self.get_album_name();
		albums 		= video_publish.publish_session.query(Ray_Video_Album).filter(Ray_Video_Album.Caption == album_name).all()
		if len(albums) == 0:
			a 		= Ray_Video_Album();
			a.Caption	= album_name
			a.Status	= 'active'
			a.Uri		= str(time.time()).replace(".","");
			a.Date		= int(time.time())
			a.Owner		= self.get_owner();
			video_publish.publish_session.add(a);
			video_publish.publish_session.commit();
			return a
		else:
			return albums[0]
	def is_all_video_ready(self):
		if os.path.exists(self.download_video_name):
			print 'file exsit'
		else:
			return False;
		if os.path.exists(self.download_video_jpg):
			print "file jgp exsit"
		else:
			return False
		if os.path.exists(self.download_video_jpg_small):
			print "file small jpg exsits"
		else:
			return False;
		return True;
	def is_publish_video_not_exsits(self,filename):
		self.publish_video_name		= video_publish.Publish_Video_Path +"/"+filename+".m4v";
		self.publish_video_jpg  	= video_publish.Publish_Video_Path +"/"+filename+".jpg";
		self.publish_video_jpg_small	= video_publish.Publish_Video_Path +"/"+filename+"_small.jpg"

		if not os.path.exists(self.publish_video_name):
			print self.publish_video_name + " not ready"
		else:
			print self.publish_video_name + " already exsits"

			return False
		if not os.path.exists(self.publish_video_jpg):
			print self.publish_video_jpg + " not ready"
		else:
		     	print self.publish_video_jpg + " already exsits"
			return False
		if not os.path.exists(self.publish_video_jpg_small):
			print self.publish_video_jpg_small + " not ready"
		else:
		     	print self.publish_video_jpg_small + " already exsits"
			return False
		return True;

	def push_video_online(self):
		shutil.copy(self.download_video_name,self.publish_video_name);
		shutil.copy(self.download_video_jpg,self.publish_video_jpg);
		shutil.copy(self.download_video_jpg_small,self.publish_video_jpg_small);

	def add_video_begin(self):
		self.ray_video.publish_video(category=self.download_video.video_product,\
					   title   =self.download_video.video_title,\
					   uri     =os.path.basename(self.download_video.video_downloadname).split('.')[0],\
					   tag     =self.download_video.video_product,\
					   des     =self.download_video.video_describe,\
					   date    =str(int(time.time())),\
					   owner   =self.get_owner(),\
					   status  ="disapproved");
		video_publish.publish_session.commit();
		if self.is_all_video_ready() and self.is_publish_video_not_exsits(str(self.ray_video.ID)):
			self.push_video_online()
			self.ray_video.Status	   ="approved"
			video_publish.publish_session.commit();
			return True
		else:
			print "del it"
			return False;


		
	def add_video_to_album(self,album):
		new_video 	    	= Ray_Video_In_Album();
		new_video.id_album 	= album.ID
		last_video_in_album = video_publish.publish_session.query(Ray_Video_In_Album).filter(Ray_Video_In_Album.id_album == album.ID).order_by(desc(Ray_Video_In_Album.obj_order)).first()
		if None == last_video_in_album: 
			new_video.id_object	= self.ray_video.ID;
			new_video.obj_order	= 0;
		else:
			new_video.id_object	= self.ray_video.ID;
			new_video.obj_order	= last_video_in_album.obj_order + 1;
		video_publish.publish_session.add(new_video);
		video_publish.publish_session.commit()
		album.ObjCount			= album.ObjCount+ 1
		album.LastObjId			= self.ray_video.ID
		video_publish.publish_session.commit()
		self.publish_video_status	= True
	def add_video_category(self):
		p  = Ray_Video_Category();
		p.Category 	= self.ray_video.Categories
		p.ID		= self.ray_video.ID
		p.Type		= 'bx_videos'
		p.Owner		= self.get_owner()
		video_publish.publish_session.add(p);
		video_publish.publish_session.commit();
	def add_video_end(self):
		if self.publish_video_status:
			self.download_video.video_status 		= "publish_suc" 
			self.download_video.video_publishname		= self.publish_video_name
		else:
		     	self.download_video.video_status 		= "publish_fail"
		video_publish.video_session.commit()
		
		return
	def video_publish(self):
		#创建发布视频对象
		if self.add_video_begin():
		#选择一个相册
			albums = self.get_album();
		#把视频对象发布到相册中
			self.add_video_to_album(albums);	
		#发布视频类型
			self.add_video_category();
		self.add_video_end();
	
			
if __name__ == '__main__':
#create session
        MovieSession                  = sessionmaker(bind= db_init.engine)
        Movie_session                 =	MovieSession()
	RayfileSession		      = sessionmaker(bind= db_init.engine_publish)
	Rayfile_session		      = RayfileSession()
	"""
	for row in Rayfile_session.query(Ray_Video_File).all():
		continue
		#print row.ID , row.Title
	"""
	## 同一个row不可以加入到2个seesion中
	## 所以这里要用video_publish的session
	for row in video_publish.video_session.query(movie_queue).filter(movie_queue.video_status == 'convert_done'):
		p = video_publish(row)
		p.video_publish();
		# 如果视频发布成功则 加入社团
		if row.video_status == "publish_suc":
			video_group = add_video_to_group();
			video_group.set_spider_video_id(str(row.id));
			# 如果视频没有group 暂时不发布
			if video_group.get_group(): #获取到id了
				video_group.set_video_id(str(p.ray_video.ID));	
				video_group.add_video();
				video_group.group_suc();
			else:
				video_group.group_fail();

